<template>
<div class="save-wrapper ui pc ">
    <!--<header class="page-header-2">{{val.name}} (ID:{{val.id}})</header>-->
    <div class="ui ordered steps mini">
        <div class="step" :class="{active: activeTag.tab.id == id}" v-for="{id, text, options=null} in tabs">
            <div class="content">
                <div class="title">{{text}}
                    <select class="ui dropdown button" v-if="options">
                            <option class="item" :value="value" v-for="{value, text} in options">{{text}}</option>
                     </select>
                </div>
            </div>
        </div>
    </div>
    <div class="ui segment">
        <component :is='activeTag.components_name' @onchange="onchange" :params="params" :op='op'></component>
    </div>
    <div class="pc-actions">
        <step-action @sclick="sclick" ref="stepAction" :sconfig="sconfig"></step-action>
    </div>
</div>
</template>
<script>
import tool from 'src/util/tool';
import util from '_util/index';
import logic from '_logic';

import stepAction from 'components/edit/addProduct/stepAction';

import product_unit from 'components/edit/addProduct/productUnit'
import productCostExplanation from 'components/edit/addProduct/productCostExplanation'
import productOrderExplanation from 'components/edit/addProduct/productOrderExplanation'
import productBuyLimt from 'components/edit/addProduct/productBuyLimt'
import productBuyStock from 'components/edit/addProduct/productBuyStock'

export default {
    data() {
        return {
            val: {},
            params: {
                type_id: "",
                data: {}
            },
            sconfig: {
                pre: {
                    disabled: true,
                },
                next: {
                    disabled: false
                },
                save: {
                    disabled: true
                },
                cancel: {}
            },
            comData: {},
            componentsList: {
                "1": "product_unit",
                "2": "productCostExplanation",
                "3": "productOrderExplanation",
                "4": "productBuyLimt",
                "5": "productBuyStock",
            },
            activeTag: {
                index: 0,
                tab: {},
                components_name: ""
            },
            tabStatus: {},
            tabs: [{
                    id: 1,
                    text: "规格配置",
                },
                {
                    id: 2,
                    text: "费用说明",
                },
                {
                    id: 3,
                    text: "预定须知",
                },
                {
                    id: 4,
                    text: "购买限制",
                },
                {
                    id: 5,
                    text: "商品库存",
                },
            ]
        }
    },
    components: {
        stepAction,
        product_unit,
        productCostExplanation,
        productOrderExplanation,
        productBuyLimt,
        productBuyStock,
    },
    watch: {
        "activeTag.index": function(val, oldval) {
            this.sconfig.pre.disabled = val == 0;
            this.sconfig.save.disabled = val != this.tabs.length - 1;
            this.sconfig.next.disabled = val == this.tabs.length - 1;
            this.activeTag.tab = this.tabs[val];
            this.activeTag.components_name = this.componentsList[this.activeTag.tab.id];
        }
    },
    methods: {
        /*设置步骤*/
        stepInit() {
            this.activeTag.index = 0;
            this.activeTag.tab = this.tabs[0];
            this.activeTag.components_name = this.componentsList[this.tabs[0].id];
            this.tabs.forEach((_, i) => {
                this.tabStatus[i + 1] = i < 10;
            });
        },
        /* component 数据回传 */
        onchange({
            name,
            data
        }) {
            this.params.data[name] = data;
        },
        /* 控制步骤 */
        sclick({
            type = ""
        }) {
            if (type == "cancel") {
                this.$router.go(-1);
                return;
            }
            let next = true;
            let data = this.params.data[this.activeTag.index + 1];
            if (data) {
				if(this.activeTag.index==0){
					data.alias_name = this.params.data[0].alias_name
				}
                Object.keys(data).forEach(key => {
                    if (data[key].is_must && data[key].value.length < 1) {
                        util.showMsg(this, 'error', `${data[key].label}为必填`);
                        next = false;
                        return;
                    }
                })
				delete data.alias_name
            } else {
                util.showMsg(this, 'error', '规格配置不能为空，请在商品类型中添加。');
                next = false;
                return;
            }
            if (!next) {
                return;
            }
            if (type == "save") {
                this.onSubmit();
                return;
            }
            if (type == "pre") {
                this.activeTag.index--;
            }
            if (type == "next") {
                this.activeTag.index++;
            }
        },
        editDataInit() {
            //this.editData
			//销售名称配置
			this.params.data[0] = {
				alias_name : {
					label: "销售别名",
					name: "alias_name",
					value: tool.nullToSpace(this.editData.alias_name),
					is_must:true,
					show_type:'input',
					maxlength:60
				}
			}

            /**
             *   规格配置
             * */


            this.params.data[1] = {}
            if (this.editData.attr.length) {
                this.editData.attr.forEach(item => {
                    this.params.data[1][item.attr_id] = {
                        attr_id: item.attr_id,
                        is_must: item.is_must,
                        label: item.attr_name,
                        value: item.value,
                        sort: item.sort,
                    }
                })
            }
            /**
             *  费用说明
             * */
            this.params.data[2] = {
                scost_in: {
                    label: "费用包含",
                    name: "scost_in",
                    value: tool.nullToSpace(this.editData.scost_in)
                },
                scost_ex: {
                    label: "费用不含",
                    name: "scost_ex",
                    value: tool.nullToSpace(this.editData.scost_ex)
                }
            };
            this.params.data[3] = {
				scontent: tool.nullToSpace(this.editData.scontent),
				srefund:tool.nullToSpace(this.editData.srefund),
                sreminder: tool.nullToSpace(this.editData.sreminder),
                snotice: tool.nullToSpace(this.editData.snotice),
				refund_time: tool.nullToSpace(this.editData.refund_time),
				useRefoundRoles:false,
            };
            ['refund_fee_extra', 'refund_fee_per', 'effect_time'].forEach(item => {
                if (this.editData[item]) {
                    this.params.data[3][item] = this.editData[item]
                }
				if (this.editData[item]>0) {
					this.params.data[3].useRefoundRoles = true
				}
            });
			if((!this.params.data[3].useRefoundRoles)&&Array.isArray(this.params.data[3].refund_time)){
				this.params.data[3].refund_time.forEach(item => {
					if (item>0) {
						this.params.data[3].useRefoundRoles = true
					}
				})
			}
            /**
             *  购买限制
             * */
            this.params.data[4] = {
                //delivery_id: "",
                need_target_date: 0,
                collect_address: '',
                confirm_time: 1,
                weekend_work: 1,
                holiday_work: 1,
                need_contact: 0,
                need_identity: '',
                identity_type: [],
                auto_delivery: 0,
                refund_rule: 1,
                msg_model: '',
                product_remark: ''
            };
            let data_4 = this.params.data[4];
            Object.keys(data_4).forEach(key => {
                data_4[key] = tool.nullToSpace(this.editData[key]);
            })

            data_4.sp_id = {
                value: this.editData.sp_id,
                is_must: true,
                label: '供应商信息'
            };
            data_4.identity_type = this.editData.identity_type.length>0 ? this.editData.identity_type.split('|') : [];
            data_4.preset_time = this.editData['preset_time'].length == 2 ? this.editData['preset_time'] : ['', ''];
            data_4.buy_total_limt = this.editData.need_identity == 99999 ? 0 : 1;
            data_4.buy_total_limt_quantity = this.editData.need_identity;
            data_4.need_guest_info = this.editData.need_identity == 0 ? 0 : 1;
            //  sp_id: {value:'',is_must:true,label:'供应商信息'},need_guest_info: 0,preset_time: ['', ''],buy_total_limt: 0,buy_total_limt_quantity: '',


            if (this.editData.is_quantity_date) {
                let _this = this,
                    start_date = tool.dateFormat(new Date(), 'yyyy-MM-dd'),
                    end_date = tool.dateFormat(new Date(new Date().getTime() + 24 * 60 * 60 * 1000 * 180), 'yyyy-MM-dd')
                util.http.getDataCom(_this, '/index/Product/getQuantityCalender', {
                    product_id: _this.editData.id,
                    start_date: start_date,
                    end_date: end_date
                }, (rs) => {
                    this.params.data[5] = {
                        is_quantity_date: _this.editData.is_quantity_date,
                        data: rs.data
                    }
                });
            } else {
                this.params.data[5] = {
                    is_quantity_date: this.editData.is_quantity_date,
                    data: {
                        price: this.editData.price,
                        quantity: this.editData.quantity
                    }
                }
            }
        },
        submitData() {
            let data = {};
            data.top_product_id = this.$route.query.top_product_id;

            data.attr = [];
			//销售名称
			data.alias_name =  this.params.data[0]?tool.nullToSpace(this.params.data[0].alias_name.value):''
            /**
             *   规格配置
             * */
            Object.keys(this.params.data[1]).forEach(item => {
                let value = this.params.data[1][item].value;
                value == '未选择' ? value = '' : null;
                data.attr.push({
                    attr_id: this.params.data[1][item].attr_id,
                    value: value,
                    sort: this.params.data[1][item].sort
                });
            });
			data.attr.sort((a, b)=>{
			  return a.sort > b.sort;
			});
            /**
             *  费用说明
             * */
            if (Object.keys(this.params.data).indexOf(2) > -1) {
                Object.keys(this.params.data[2]).forEach(item => {
                    data[item] = this.params.data[2][item].value
                });
            }
            /**
             *  预定须知
             * */
            if (this.params.data[3]) {
                Object.keys(this.params.data[3]).forEach(item => {
                    data[item] = this.params.data[3][item]
                });
            }
            /**
             *  购买限制
             * */
            let data_4 = this.params.data[4];
            if (data_4) {
                Object.keys(data_4).forEach(item => {
                    if (data_4[item].is_must) {
                        data[item] = data_4[item].value
                    } else {
                        data[item] = data_4[item]
                    }
                });
                data.identity_type = data.identity_type.join('|');
                if (data_4.need_guest_info == 1 && data_4.buy_total_limt == 1) {
                    data.need_identity = data_4.buy_total_limt_quantity
                } else if (data_4.need_guest_info == 0) {
                    data.need_identity = 0
                } else {
                    data.need_identity = 99999
                }
            }


            let data_5 = this.params.data[5];
            if (data_5) {
                data.is_quantity_date = data_5.is_quantity_date;
                if (data.is_quantity_date * 1) {
                    data.quantity_data = data_5.data
                } else {
                    data.quantity = data_5.data.quantity;
                    data.price = data_5.data.price;
                }
            }
            if (this.op != 'insert') {
                data = { ...this.editData,
                    ...data
                }
            }
            return data
        },
        onSubmit() {

            //let url = tool.getApi(this,'ProductType', 'bindAttr');
            let _this = this;
            let data = this.submitData();
            if (_this.op != 'insert') {
                data.top_product_id = this.editData.top_product_id;
            }
            if (_this.flag == 'copy') {
                delete data.id
            }
            if (this.params.data[5]) {
                let stockUrl = `/index/Product/editQuantityCalender`,
                    dataUrl = this.op == 'insert' ? '/index/Product/insert' : '/index/Product/update',
                    callBackUrl = this.op == 'insert' ? '/page/list?ctl=TopProduct&title=商品管理' : `/page/list?ctl=Product&top_product_id=${this.editData.top_product_id}`;
                util.http.SR(this, dataUrl, data, '操作成功', (rs) => {
                    _this.$router.push(callBackUrl);
                });

            }
        },
    },
    computed: {
        titleType() {
            return logic.edit.get_titleType(this);
        },
        ctl() {
            return this.$route.query.ctl;
        },
        flag() {
            return this.$route.query.flag;
        },
        op() {
            return util.getOp(this)
        },
        editData() {
            return this.$store.state.global.editVo;
        }

    },
    props: [],
    created() {
        //this.val=util.store.get(this, 'editVo');
        if (this.op != 'insert') {
            this.editDataInit()
        }
        this.$nextTick(() => {
            this.stepInit();
        });

        // this.$refs.step.
    },
}
</script>
<style rel="stylesheet/less" scoped lang="less">
@import "../../common/style/mixin";

.page-header-2 {
    font-size: 16px;
    padding: 10px;
    border-bottom: 1px solid rgba(34, 36, 38, .15);
}

.pc {
    padding-bottom: 60px;
    &-actions {
        position: fixed;
        left: 210px;
        right: 20px;
        bottom: 10px;
        padding-top: 10px;
        background: linear-gradient(to top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0) 100%);
    }
    &-block {
        &-title {
            font-size: 14px;
            height: 26px;
            line-height: 26px;
            margin-bottom: 10px;
        }
    }
}
</style>
